package pikasial.utils;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.swing.ProgressMonitor;
import javax.swing.SwingUtilities;

import pikasial.images.PhotosListModel;
import pikasial.images.PikImage;

public class ChargeurImages {

	private static ChargeurImages instance = new ChargeurImages();
	private ExecutorService pool;
	private PikImage imageToLoad;
	private ArrayList<Callable<Integer>> collec;
	private Iterator<PikImage> containerIterator;

	private ChargeurImages() {
		pool = Executors.newCachedThreadPool();
	}

	private synchronized PikImage getNextImage() {return containerIterator.next(); }

	@Deprecated
	public void chargerVignettesAlbum(final PhotosListModel plm) throws ExecutionException {
		final int[] count = {0};
		System.out.println("Salut");
		containerIterator = plm.getAlbum().getAllImages().iterator();
		collec = new ArrayList<Callable<Integer>>();
		final int size = plm.getAlbum().getImageCount();
		final ProgressMonitor progress = new ProgressMonitor(pikasial.Pikasial.getFrame(),
				"Chargement des images","",
				0,size);
		progress.setProgress(count[0]);
		System.out.println("Hey "+size);
		for (int i=0; i < size; i++) {
			collec.add(new Callable<Integer>() {
				public Integer call() throws Exception {
					try {
						PikImage pik = getNextImage();
						pik.getVignette();
						plm.addImage(pik);
					} catch (NoSuchElementException nsee) {System.err.println("pas cool");}
					return 1;
				}
			});
		}

		try {
			List<Future<Integer>> results = pool.invokeAll(collec);
			for (Future<Integer> fut : results) {
				System.out.println(""+count[0]);
				count[0] += fut.get();
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						progress.setProgress(count[0]);
						progress.setNote(String.format("Terminé à %d%%",count[0]/size*100));
					}
				});
			}
			progress.close();
		} catch (InterruptedException ie) {
			System.err.println("Interrompu !!!");
		}
	}

	public BufferedImage chargerImage(PikImage pik) throws ExecutionException {
		imageToLoad = pik;
		Future<BufferedImage> f = pool.submit(new Callable<BufferedImage>() {
			public BufferedImage call() throws Exception {
				return imageToLoad.getImage();
			}
		});
		BufferedImage bi = null;

		try {
			bi = f.get();
		} catch (InterruptedException ie) {
			System.err.println("Interrompu");
		}
		return bi;
	}

	public static ChargeurImages getInstance() { return instance; }
}
